<?php

namespace app\api\controller;
use app\common\controller\Base;
use think\Controller;
vendor ('aliyuncs.oss-sdk-php.autoload');
use OSS\OssClient;
use OSS\Core\OssException;
class Uploader extends Base
{
    /**
     * 上传图片到本地
     */
    public function uploadImage()
    {
        try {
            $file = $this->request->file('file');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'image');
            if ($info) {
                $upload_image = unserialize(config('upload_image'));
                if ($upload_image['is_thumb'] == 1 || $upload_image['is_water'] == 1 || $upload_image['is_text'] == 1) {
                    $object_image = \think\Image::open($info->getPathName());
                    // 图片压缩
                    if ($upload_image['is_thumb'] == 1) {
                        $object_image->thumb($upload_image['max_width'], $upload_image['max_height']);
                    }
                    // 图片水印
                    if ($upload_image['is_water'] == 1) {
                        $object_image->water(ROOT_PATH . trim($upload_image['water_source'], '/'), $upload_image['water_locate'], $upload_image['water_alpha']);
                    }
                    // 文本水印
                    if ($upload_image['is_text'] == 1) {
                        $font = !empty($upload_image['text_font']) ? trim($upload_image['text_font'], '/') : 'vendor/topthink/think-captcha/assets/zhttfs/1.ttf';
                        $object_image->text($upload_image['text'], ROOT_PATH . $font, $upload_image['text_size'], $upload_image['text_color'], $upload_image['text_locate'], $upload_image['text_offset'], $upload_image['text_angle']);
                    }
                    $object_image->save($info->getPathName());
                }
                return ['code' => 1, 'url' => '/upload/image/' . str_replace('\\', '/', $info->getSaveName())];
            } else {
                return ['code' => 0, 'msg' => $file->getError()];
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 上传文件到本地
     */
    public function uploadFile()
    {
        try {
            $file = $this->request->file('file');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'file');
            if ($info) {
                return ['code' => 1, 'url' => '/upload/file/' . str_replace('\\', '/', $info->getSaveName())];
            } else {
                return ['code' => 0, 'msg' => $file->getError()];
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 上传视频到本地
     */
    public function uploadVideo()
    {
        try {
            $file = $this->request->file('file');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'video');
            if ($info) {
                return ['code' => 1, 'url' => '/upload/video/' . str_replace('\\', '/', $info->getSaveName())];
            } else {
                return ['code' => 0, 'msg' => $file->getError()];
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 阿里云Oss上传类
     */
    function new_oss(){
        if(empty(config('KeyID') || empty(config('KeySecret')))){
            return ['code' => 0, 'msg' => '请先配置阿里云oss'];
        }else{
            $oss=new OssClient(config('KeyID'),config('KeySecret'),config('EndPoint'));
            return $oss;
        }
    }

    /**
     * 阿里云Oss上传实例（通用）
     */
    public function ossupload()
    {
        try {
            $file = $this->request->file('file');
            $param = $this->request->param();
            if(empty($param)) {
                $param['type']='file';
            };
            $ossClient =$this->new_oss();
            $ossClient->uploadFile(config('Bucket'), 'files'.is_admin_login().'/'.$param['type'].'/'.$file->getInfo('name'),$file->getInfo()['tmp_name']);
            $url='//'.config('Bucket').'.'.config('EndPoint').'/'.'files'.is_admin_login().'/'.$param['type'].'/'.$file->getInfo('name');
            if($this->insert('Material', ['type'=>$param['type'],'uid'=>is_admin_login(),'original_name'=>$file->getInfo('name'),'oss_name'=>'files'.is_admin_login().'/'.$param['type'].'/'.$file->getInfo('name'),'oss_url'=>$url,'addtime'=>date('Y-m-d H:i:s', time())])===true){
                return ['code' => 1, 'url' => $url];
            }else{
                return ['code' => 0, 'msg' => $this->errorMsg];
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    /**
     *编辑器上传图片
     */
    function wangEditorUp(){
        $file = $this->request->file('image');
        $data = model('system')->where('name', 'upload_image')->find();
        $upload=unserialize($data['value']);
        if($upload['location']==1){
            return $this->wangEditorUpLocal($file);
        }else{
            return $this->wangEditorUpOss($file);
        }
    }
    /**
     *编辑器上传图片到oss
     */
    function wangEditorUpOss($file){
        try {
            $param['type']='image';
            $ossClient =$this->new_oss();
            $ossClient->uploadFile(config('Bucket'), 'files'.is_admin_login().'/'.$param['type'].'/'.$file->getInfo('name'),$file->getInfo()['tmp_name']);
            $url='//'.config('Bucket').'.'.config('EndPoint').'/'.'files'.is_admin_login().'/'.$param['type'].'/'.$file->getInfo('name');
            return json_encode(['errno' => 0, 'data' =>[$url]]);
        } catch (\Exception $e) {
            return json_encode(['errno' => 1, 'data' => $e->getMessage()]);
        }
    }
    /**
     *编辑器上传图片到本地
     */
    function wangEditorUpLocal($file){
        try {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'image');
            if ($info) {
                $upload_image = unserialize(config('upload_image'));
                if ($upload_image['is_thumb'] == 1 || $upload_image['is_water'] == 1 || $upload_image['is_text'] == 1) {
                    $object_image = \think\Image::open($info->getPathName());
                    // 图片压缩
                    if ($upload_image['is_thumb'] == 1) {
                        $object_image->thumb($upload_image['max_width'], $upload_image['max_height']);
                    }
                    // 图片水印
                    if ($upload_image['is_water'] == 1) {
                        $object_image->water(ROOT_PATH . trim($upload_image['water_source'], '/'), $upload_image['water_locate'], $upload_image['water_alpha']);
                    }
                    // 文本水印
                    if ($upload_image['is_text'] == 1) {
                        $font = !empty($upload_image['text_font']) ? trim($upload_image['text_font'], '/') : 'vendor/topthink/think-captcha/assets/zhttfs/1.ttf';
                        $object_image->text($upload_image['text'], ROOT_PATH . $font, $upload_image['text_size'], $upload_image['text_color'], $upload_image['text_locate'], $upload_image['text_offset'], $upload_image['text_angle']);
                    }
                    $object_image->save($info->getPathName());
                }
                return json_encode(['errno' => 0, 'data' =>['/upload/image/' . str_replace('\\', '/', $info->getSaveName())]]);
            } else {
                return json_encode(['errno' => 1, 'data' => $file->getError()]);
            }
        } catch (\Exception $e) {
            return json_encode(['errno' => 1, 'data' => $e->getMessage()]);
        }
    }
}